import React, { useState, useEffect } from "react";
import { Table, Button, Popconfirm } from "antd";
import { $list, $del } from "../../apis/roleListApi";
import AddRole from "./AddRole";

export default function role() {
  const [roleList, setRoleList] = useState([]);
  const [keyId, setkeyId] = useState(0);

  const columns = [
    {
      title: "角色编号",
      dataIndex: "key",
      width: "100px",
    },
    {
      title: "角色名称",
      dataIndex: "name",
      width: "250px",
    },
    {
      title: "操作",
      key: "action",
      width: "4px",
      render: (ret) => (
        <Button
          size="small"
          style={{ borderColor: "orange", color: "orange" }}
          onClick={() => {
            edit(ret.key);
          }}
        >
          编辑
        </Button>
      ),
    },
    {
      title: "删除",
      key: "action",
      render: (ret) => (
        <Popconfirm
          title="提示"
          description="确认删除吗?"
          onConfirm={() => {
            del(ret.key);
          }}
          okText="确定"
          cancelText="取消"
        >
          <Button danger size="small">
            删除
          </Button>
        </Popconfirm>
      ),
    },
  ];
  useEffect(() => {
    loadList();
  }, []);
  const loadList = () => {
    $list().then((res) => {
      setRoleList(res);
    });
  };
  // 编辑用户
  const edit = (keyId) => {
    setOpen(true);
    setkeyId(keyId);
  };
  // 删除用户
  const del = async (key) => {
    await $del({ key });
    loadList();
    alert("删除成功");
  };

  // 抽屉开关
  const [open, setOpen] = useState(false);
  const showDrawer = () => {
    setOpen(true);
  };

  return (
    <>
      <Button className="add" onClick={showDrawer}>
        添加
      </Button>
      <Table columns={columns} dataSource={roleList} />
      <AddRole
        open={open}
        setOpen={setOpen}
        loadList={loadList}
        keyId={keyId}
        setkeyId={setkeyId}
      ></AddRole>
    </>
  );
}
